<template>
  <el-dialog :title="'批量手动签到'" :visible.sync="visible" width="800px" :close-on-click-modal="false" append-to-body>
    <el-form ref="dataForm" :model="dataForm" :rules="dataRule" size="small" label-width="120px" label-position="right">
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="签到日期" prop="signDate">
            <el-date-picker v-model="dataForm.signDate" type="date" placeholder="请选择签到日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{ width: '100%' }" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签到时段" prop="period">
            <el-select v-model="dataForm.period" placeholder="请选择时段" :style="{ width: '100%' }">
              <el-option label="上午" value="AM" />
              <el-option label="下午" value="PM" />
              <el-option label="晚上" value="EVE" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签到状态" prop="status">
            <el-select v-model="dataForm.status" placeholder="请选择状态" :style="{ width: '100%' }">
              <el-option label="正常签到" value="Normal" />
              <el-option label="迟到" value="Late" />
              <el-option label="请假" value="Leave" />
              <el-option label="早退" value="EarlyLeave" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签到时间" prop="signTime">
            <el-date-picker v-model="dataForm.signTime" type="datetime" placeholder="请选择签到时间" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" :style="{ width: '100%' }" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dataForm.remark" type="textarea" placeholder="请输入备注" :rows="2" maxlength="500" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <!-- 老师搜索和添加区域 -->
    <div class="teacher-search-section">
      <h4>添加签到老师</h4>
      <el-row :gutter="15">
        <el-col :span="16">
          <el-select
            v-model="searchTeacherId"
            placeholder="搜索并选择老师"
            filterable
            remote
            :remote-method="searchTeachers"
            :loading="searchLoading"
            clearable
            :style="{ width: '100%' }"
            @change="addTeacher">
            <el-option
              v-for="item in availableTeachers"
              :key="item.id"
              :label="item.teacherName"
              :value="item.id"
              :disabled="isTeacherSelected(item.id)">
              <span style="float: left">{{ item.teacherName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.campusName }}</span>
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="addAllAvailableTeachers" :disabled="availableTeachers.length === 0">
            添加全部
          </el-button>
          <el-button @click="clearAllTeachers" :disabled="selectedTeachers.length === 0">
            清空全部
          </el-button>
        </el-col>
      </el-row>
    </div>
    
    <!-- 选中的老师列表 -->
    <div class="selected-teachers">
      <h4>选中的老师 ({{ selectedTeachers.length }}人)</h4>
      <el-table :data="selectedTeachers" size="mini" max-height="300" border>
        <el-table-column prop="teacherName" label="老师姓名" width="120" />
        <el-table-column prop="idCard" label="身份证号" width="180">
          <template slot-scope="scope">
            {{ scope.row.idCard ? scope.row.idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2') : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="campusName" label="所属校区" />
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="removeTeacher(scope.$index)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :loading="loading" :disabled="selectedTeachers.length === 0">批量签到</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { batchManualSignIn, getTrainSignRecordList } from '@/api/campus/trainSignRecord'
import { getTrainParticipantList } from '@/api/campus/trainOrderItem'
import signTimeValidator from '@/utils/signTimeValidator'
import auditLogger from '@/utils/auditLogger'

export default {
  data() {
    return {
      visible: false,
      loading: false,
      trainId: '',
      selectedTeachers: [],
      availableTeachers: [],
      allTeachers: [], // 保存完整的老师列表用于搜索
      searchTeacherId: '',
      searchLoading: false,
      searchKeyword: '',
      dataForm: {
        trainId: '',
        signDate: '',
        period: '',
        status: 'Normal',
        signTime: '',
        remark: ''
      },
      dataRule: {
        signDate: [{ required: true, message: '请选择签到日期', trigger: 'change' }],
        period: [{ required: true, message: '请选择签到时段', trigger: 'change' }],
        status: [{ required: true, message: '请选择签到状态', trigger: 'change' }],
        signTime: [
          { required: true, message: '请选择签到时间', trigger: 'change' },
          { validator: this.validateSignTime, trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    // 监听签到日期和时段变化，重新加载可用老师
    'dataForm.signDate'() {
      if (this.dataForm.signDate && this.dataForm.period && this.trainId) {
        this.loadAvailableTeachers()
        this.selectedTeachers = [] // 清空已选择的老师
      }
    },
    'dataForm.period'() {
      if (this.dataForm.signDate && this.dataForm.period && this.trainId) {
        this.loadAvailableTeachers()
        this.selectedTeachers = [] // 清空已选择的老师
      }
    }
  },
  methods: {
    init(trainId, selectedRecords) {
      this.trainId = trainId
      this.dataForm.trainId = trainId
      this.selectedTeachers = selectedRecords || []
      this.visible = true
      this.$nextTick(() => {
        this.$refs.dataForm.resetFields()
        this.setDefaultValues()
        // 设置默认值后再加载可用老师
        if (this.dataForm.signDate && this.dataForm.period) {
          this.loadAvailableTeachers()
        }
      })
    },
    setDefaultValues() {
      const now = this.$moment()
      this.dataForm.signDate = now.format('YYYY-MM-DD')
      
      // 使用智能默认时段
      this.dataForm.period = signTimeValidator.getSmartDefaultPeriod()
      
      // 使用智能默认时间
      this.dataForm.signTime = signTimeValidator.getSmartDefaultTime(
        this.dataForm.period, 
        this.dataForm.signDate
      )
      
      this.dataForm.status = 'Normal'
    },
    async loadAvailableTeachers() {
      try {
        // 获取所有参训老师
        const participantRes = await getTrainParticipantList(this.trainId)
        const allParticipants = participantRes.data || []
        
        // 获取已签到的老师列表
        const signRecordRes = await getTrainSignRecordList({
          trainId: this.trainId,
          signDate: this.dataForm.signDate,
          period: this.dataForm.period
        })
        
        const signedTeacherIds = new Set()
        if (signRecordRes.data && signRecordRes.data.list) {
          signRecordRes.data.list.forEach(record => {
            signedTeacherIds.add(record.teacherId)
          })
        }
        
        // 过滤掉已签到的老师
        const unsignedTeachers = allParticipants.filter(teacher => 
          !signedTeacherIds.has(teacher.teacherId || teacher.id)
        )
        
        this.allTeachers = unsignedTeachers
        this.availableTeachers = [...unsignedTeachers]
        
        if (unsignedTeachers.length === 0) {
          this.$message.info('当前时段所有老师都已签到')
        }
      } catch (err) {
        console.error('获取参训老师列表失败:', err)
        this.$message.error('获取参训老师列表失败，请重试')
        this.availableTeachers = []
        this.allTeachers = []
      }
    },
    searchTeachers(keyword) {
      if (keyword) {
        this.searchLoading = true
        this.searchKeyword = keyword
        // 从完整的老师列表中进行本地搜索
        this.availableTeachers = this.allTeachers.filter(teacher => 
          teacher.teacherName.includes(keyword) || 
          (teacher.idCard && teacher.idCard.includes(keyword))
        )
        this.searchLoading = false
      } else {
        this.availableTeachers = [...this.allTeachers]
      }
    },
    isTeacherSelected(teacherId) {
      return this.selectedTeachers.some(teacher => 
        (teacher.teacherId || teacher.id) === teacherId
      )
    },
    addTeacher(teacherId) {
      if (!teacherId) return
      
      const teacher = this.availableTeachers.find(item => item.id === teacherId)
      if (teacher && !this.isTeacherSelected(teacherId)) {
        this.selectedTeachers.push({
          id: teacher.id,
          teacherId: teacher.id,
          teacherName: teacher.teacherName,
          idCard: teacher.idCard,
          campusName: teacher.campusName
        })
        this.searchTeacherId = ''
        this.$message.success(`已添加老师：${teacher.teacherName}`)
      }
    },
    addAllAvailableTeachers() {
      let addedCount = 0
      this.availableTeachers.forEach(teacher => {
        if (!this.isTeacherSelected(teacher.id)) {
          this.selectedTeachers.push({
            id: teacher.id,
            teacherId: teacher.id,
            teacherName: teacher.teacherName,
            idCard: teacher.idCard,
            campusName: teacher.campusName
          })
          addedCount++
        }
      })
      if (addedCount > 0) {
        this.$message.success(`已添加 ${addedCount} 位老师`)
      } else {
        this.$message.info('没有可添加的老师')
      }
    },
    clearAllTeachers() {
      this.$confirm('确认清空所有已选择的老师吗？', '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.selectedTeachers = []
        this.$message.success('已清空所有老师')
      })
    },
    removeTeacher(index) {
      const teacher = this.selectedTeachers[index]
      this.selectedTeachers.splice(index, 1)
      this.$message.success(`已移除老师：${teacher.teacherName}`)
    },
    async validateSignTime(rule, value, callback) {
      if (!value || !this.dataForm.signDate || !this.dataForm.period) {
        callback()
        return
      }
      
      try {
        // 使用统一的验证工具进行基础验证
        const basicResult = signTimeValidator.validateBasicRules(
          value, 
          this.dataForm.signDate, 
          this.dataForm.period
        )
        
        if (!basicResult.valid) {
          callback(new Error(basicResult.message))
          return
        }
        
        // 批量签到时不进行服务端验证（性能考虑），只做基础验证
        callback()
      } catch (error) {
        console.error('签到时间验证失败:', error)
        callback(new Error('签到时间验证失败，请检查输入'))
      }
    },
    dataFormSubmit() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if (this.selectedTeachers.length === 0) {
            this.$message.warning('请选择要签到的老师')
            return
          }
          
          // 详细的确认信息
          const teacherNames = this.selectedTeachers.map(t => t.teacherName).join('、')
          const confirmMessage = 
            `确认为以下 ${this.selectedTeachers.length} 位老师进行批量手动签到吗？\n\n` +
            `老师列表：${teacherNames}\n\n` +
            `签到信息：\n` +
            `• 签到日期：${this.dataForm.signDate}\n` +
            `• 签到时段：${this.getPeriodLabel(this.dataForm.period)}\n` +
            `• 签到状态：${this.getStatusLabel(this.dataForm.status)}\n` +
            `• 签到时间：${this.dataForm.signTime}\n` +
            `• 备注：${this.dataForm.remark || '无'}`
          
          this.$confirm(confirmMessage, '确认批量签到', {
            confirmButtonText: '确定签到',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: false
          }).then(() => {
            this.loading = true
            const submitData = {
              ...this.dataForm,
              method: 'MANUAL', // 手动签到
              teacherIds: this.selectedTeachers.map(item => item.teacherId || item.id)
            }
            
            batchManualSignIn(submitData).then(async res => {
              // 记录批量审计日志
              try {
                const logDataList = auditLogger.createBatchSignLogData(
                  this.selectedTeachers,
                  this.dataForm,
                  '批量手动签到操作'
                )
                await auditLogger.logBatchOperations(logDataList)
              } catch (logError) {
                console.warn('批量审计日志记录失败:', logError)
              }
              
              this.$message({
                message: res.msg || `批量签到成功，共处理 ${this.selectedTeachers.length} 位老师`,
                type: 'success',
                duration: 2000,
                onClose: () => {
                  this.visible = false
                  this.loading = false
                  this.$emit('refresh')
                }
              })
            }).catch(async error => {
              // 记录批量失败日志
              try {
                const logDataList = auditLogger.createBatchSignLogData(
                  this.selectedTeachers,
                  this.dataForm,
                  '批量手动签到操作失败'
                )
                for (const logData of logDataList) {
                  await auditLogger.logFailure(logData, error)
                }
              } catch (logError) {
                console.warn('批量失败日志记录失败:', logError)
              }
              
              this.loading = false
            })
          })
        }
      })
    },
    getPeriodLabel(period) {
      return signTimeValidator.getPeriodLabel(period)
    },
    getStatusLabel(status) {
      return signTimeValidator.getStatusLabel(status)
    }
  }
}
</script>

<style lang="scss" scoped>
.teacher-search-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  
  h4 {
    margin: 0 0 15px 0;
    color: #333;
    font-size: 14px;
    font-weight: 600;
  }
}

.selected-teachers {
  margin-top: 20px;
  
  h4 {
    margin-bottom: 10px;
    color: #333;
    font-size: 14px;
    font-weight: 600;
    
    &::before {
      content: '';
      display: inline-block;
      width: 3px;
      height: 16px;
      background-color: #409eff;
      margin-right: 8px;
      vertical-align: middle;
    }
  }
  
  :deep(.el-table) {
    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

:deep(.el-select) {
  .el-select__tags {
    max-height: 100px;
    overflow-y: auto;
  }
}
</style>